package com.kp.ai.controller;

import com.kp.ai.enums.FunctionEnums;
import com.kp.ai.log.LoggingAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;

import static com.kp.ai.constant.BookingConstant.DEFAULT_ROLE;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;
/**
 * 模型对话接口
 */
@RestController
@CrossOrigin
public class OpenAiController {
    private final ChatClient chatClient;
	@Autowired
    public OpenAiController(ChatClient.Builder chatClientBuilder, VectorStore vectorStore, ChatMemory chatMemory) {
        this.chatClient = chatClientBuilder
                .defaultSystem(DEFAULT_ROLE)
                .defaultAdvisors(
                        new PromptChatMemoryAdvisor(chatMemory),
						new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()), // RAG
                        new LoggingAdvisor())
				.defaultFunctions(FunctionEnums.getFunctions()) // FUNCTION CALLING
				.build();

	}
    @CrossOrigin
    @GetMapping(value = "/ai/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStreamAsString(@RequestParam(value = "message", defaultValue = "你好") String message) {
		String chatId = "001";
        return  chatClient.prompt()
				.system(s -> s.param("current_date", LocalDate.now().toString()))//设置变量
				.advisors(a ->  a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100))//设置聊天记忆 检索大小100条
				.user(message)//传入用户对话信息
				.stream()//开启流式响应内容
				.content()//输出内容
				.concatWith(Flux.just("[complete]"));//定义一个结束变量，告诉前端，不然前端不知道对话什么时候结束

    }


}
